import { Component } from '@angular/core';
import { IonicPage, NavController, ViewController, NavParams } from 'ionic-angular';
import { HttpProvider } from '../../providers/http/http';
import { StorageProvider } from '../../providers/storage/storage';
import { DialogProvider } from '../../providers/dialog/dialog';
import { EventProvider } from '../../providers/event/event';
import { UserInfoProvider } from '../../providers/user-info/user-info';
import { Network } from '@ionic-native/network';
import { DeviceInfoDataService } from '../../providers/service/deviceInfo-data.service';
import { OrderDataService } from '../../providers/service/order-data.service';

/**
 * Generated class for the CenterPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
	selector: 'page-center',
	templateUrl: 'center.html',
})
export class CenterPage {

	// balance: string;
	// local_balance: string;
	// nickname: string;
	// member_id: any;
	// phone: any;

	//  这是全局变量
	public data = { img: null };
	//有网状态=1 断网=0
	Internet = 1;

	// 用户信息
	userInfo: user_info = new user_info();

	userPhone: any;

	constructor(
		public navCtrl: NavController,
		public viewCtrl: ViewController,
		public navParams: NavParams,
		public http: HttpProvider,
		public storage: StorageProvider,
		public dialog: DialogProvider,
		public eventsPvd: EventProvider,
		public user: UserInfoProvider,
		private network: Network,
		public deviceInfo: DeviceInfoDataService,
		public order: OrderDataService, ) { }



	ionViewDidLoad() {
		console.log('ionViewDidLoad CenterPage');
		// this.userInfo = this.user.getuserInfo();
		// console.log(this.userInfo);
		// this.member_id = this.userInfo.member_id;
		// this.balance = this.userInfo.balance;
		// this.local_balance = this.userInfo.local_balance;
		// this.nickname=this.userInfo.nickname;
		// this.phone=this.userInfo.phone;
		if (this.network.type !== 'none'  && this.network.type !== '2g') {
			this.Internet = 1;
			this.getImg();
		} else if (this.network.type === 'none' || this.network.type === '2g') {
			this.Internet = 0;
		}
		this.userPhone = this.phone();


		// this.storage.getStorage("login_info").then(res => {
		// 	console.log(res);
		// 	if (res != undefined) {
		// 		this.balance = res['balance']
		// 		this.local_balance = res['local_balance']
		// 		this.nickname = res['nickname']
		// 		this.phone = res['phone']
		// 		this.member_id = res['member_id']
		// 		this.getImg();

		// 	}
		// });

		// this.eventsPvd.bindEvents(this.eventsPvd.EVENT_CENTER).then(success => {
		// 	//数据拉取
		// 	console.log('触发事件');
		// 	const res = this.http.postJson('', 'member/member/view?id=' + this.member_id, {}, '')
		// 		.then(res => {
		// 			if (res['status'] == 200) {
		// 				this.balance = res['data']['balance'];
		// 			}
		// 		});
		// });

	}

	async ionViewWillEnter() {
		// this.eventsPvd.unbindEvents(this.eventsPvd.EVENT_CENTER);
		console.log('ionViewDidLoad CenterPage33333');
		if (this.network.type !== 'none'  && this.network.type !== '2g') {
			this.Internet = 1;
		} else if (this.network.type === 'none' || this.network.type === '2g') {
			this.Internet = 0;
		}
		this.userInfo = this.user.getuserInfo();
		if (this.network.type !== 'none'  && this.network.type !== '2g') {
			this.login();
			await this.uploadOrder();
			await this.uploadDeviceInfo();
		}
	}


	skipToAccount() {
		this.navCtrl.push('AccountPage');
	}
	skipToPersionalMessage() {
		this.navCtrl.push("PersonalMessagePage");
	}
	skipToChargingRecord() {
		this.navCtrl.push("ChargingListPage");
	}
	skipToSetting() {
		this.navCtrl.push('SettingPage');
	}
	skipTocoupon() {
		this.navCtrl.push('MyCouponsPage');
	}
	skipToComplainRecordPage() {
		this.navCtrl.push('ComplainRecordPage');
	}
	account() {
		this.navCtrl.push('AccountPage');
	}
	localaccount() {
		this.navCtrl.push('LoaclAccountPage');
	}
	skipToHelpPage() {
	    this.navCtrl.push('HelpPage');//帮助
  	}
	skipToQuestionAndAnswerPage() {
	    this.navCtrl.push('QuestionAndAnswerPage');
  	}
	accountHelp() {
		this.dialog.showAlert('账户余额说明', '账户余额仅可以用于支付充电费用，不可转移或转赠。');
	}
	localHelp() {
		this.dialog.showAlert('本地余额说明', '<p class="tip1">本地余额仅可在离线状态下支付充电费用；本地余额最高仅允许储值30元；本地余额不能转回账户余额、转移、转赠或退款。鉴于本地余额是以您账户可合法有效使用为前提条件，本地余额在如下情形下将会失效：</p><p class="tip">1.您主动注销用户账号；</p><p class="tip">2.您主动卸载鸣智智充APP；</p><p class="tip">3.因涉嫌作弊导致您的用户账号被冻结或关闭；</p><p class="tip">4.其他根据用户协议、相关说明或政府法律法规导致我们无法向您提供或停用的情形。</p>');
	}

	//获取图片方法
	getImg() {

		this.http.postJson('', 'system/middlefile/index', {
			"joinwith": ["photos"],
			"where": ["and", ["=", "product_id", this.user.userInfo.member_id], ["=", "file_type_id", "1"], ["=", "tables", "1"]],
			"limit": 0
		}, '').then(res => {
			// console.log(res)
			if (res['status'] == 200) {
				this.getFile_one(res['data']);
			}
		});
		// console.log(this.data);
	}




	//    把数组数据遍历,重新组成新的数据Push到数组里
	getFile_one(data) {
		//图片参数为空,赋给用户默认的头像
		if (data.length == 0) {
			this.data.img = "./assets/imgs/user.png";
		}
		else if (data[0].photos) {
			// console.log(data[0].photos);
			this.data.img = this.http.APP_IMG + data[0].photos.url;
		}
	}

	//隐藏手机号码
	phone() {
		//phone1截取手机号前3位
		var phone1 = this.user.userInfo.phone.substring(3, 0)
		//var phone1=this.phone_name.substring(0,3)//截取时包括前不包括后面，下标从0开始
		console.log(phone1)
		//phone2隐藏手机号
		var phone2 = "****"
		//phone3截取到手机号7-11位，下标从0开始
		var phone3 = this.user.userInfo.phone.substring(7)
		// console.log(phone3)
		var phone4 = phone1 + phone2 + phone3
		return phone4;

	}

	/**
 * 获取用户信息
 */
	async login() {
		//   await this.storage.getStorage("login_info").then(res => {
		// 	if(res != undefined) {
		// 		this.userInfo = res;
		// 	}
		// });;
		// console.log(this.userInfo);
		const res = await this.http.postJson('', 'member/member/view?id=' + this.userInfo.member_id, {}, '')
			.then(res => {
				console.log(res)
				if (res['status'] == 200) {
					res['data']['password'] = this.userInfo.password;
					res['data']['isAutomaticLogon'] = this.userInfo.isAutomaticLogon;
					this.userInfo = res['data'];
					this.user.setuserInfo(this.userInfo);
					// this.storage.saveStorage("login_info", res['data']);
					// this.http.setAuthorization(res['data']['access_token']);//该令牌唯一表示该用户、用户的组和用户的特权。系统使用令牌控制用户可以访问哪些安全对象，并控制用户执行相关系统操作的能力
					// this.navCtrl.push('CenterPage');
				}
			});
	}


	/**
	 * 上传原始设备记录
	 */
	async uploadDeviceInfo() {
		// 上传原始设备记录
		let b = await this.deviceInfo.find((deviceInfo) => deviceInfo.key !== '' && deviceInfo.upload == 0)//找出订单信息 0没有上传
		if (b.length > 0) {
			for (var i = 0; i < b.length; i++) {
				const key = b[i].key;
				let time = new Date((parseInt((b[i].datetime[0] + b[i].datetime[1]), 16) + 2000), (parseInt((b[i].datetime[2] + b[i].datetime[3]), 16) - 1), parseInt((b[i].datetime[4] + b[i].datetime[5]), 16), parseInt((b[i].datetime[6] + b[i].datetime[7]), 16), parseInt((b[i].datetime[8] + b[i].datetime[9]), 16), parseInt((b[i].datetime[10] + b[i].datetime[11]), 16));
				// this.dialog.showAlert('time提示', JSON.stringify(time.getTime().toString().slice(0, 10)));
				let timeLength = time.getTime().toString().slice(0, 10);
				if (timeLength.length < 10) {
					this.deviceInfo.delete((a) => a.key === b[i].key);
					continue;
				}
				// this.dialog.showAlert('info提示', JSON.stringify(b[i]));
				let info = {
					id: b[i].rc_index,
					charge_time_start: time.getTime().toString().slice(0, 10),
					charge_time_end: (time.getTime() + (parseInt(b[i].chargingtime) * 60 * 60 * 1000)).toString().slice(0, 10),
					charge_time_org: parseInt(b[i].chargingtimerequest).toString(),
					// charge_time_start: new Date().getTime().toString().slice(0, 10),
					// charge_time_end: (new Date().getTime() + (parseInt(b[i].chargingtime) * 60 *60) ).toString().slice(0, 10),
					charge_time: parseInt(b[i].chargingtime).toString(),
					power_unit_id: b[i].power_unit_id,
					member_id: parseInt(b[i].userid),
					abnormal: b[i].abnormal,
					notifyInfo: b[i].notifyInfo,
				}
				//登录时把订单信息存入服务器
				const create = await this.http.postJson('', 'business/chargingpr/create', info, '');
				// this.dialog.showAlert('500提示', JSON.stringify(create));
				if (create['status'] === 200) {
					await this.deviceInfo.delete((a) => a.key === b[i].key);
				} else {
					if (create['code'] === 0) {
						let li = await this.deviceInfo.delete((a) => a.key === b[i].key);
						// this.dialog.showAlert('500提示', JSON.stringify(li));
					}
				}
				// if (create['status'] === 500) {
				// 	this.dialog.showAlert('500提示', JSON.stringify(key));
				// 	if (create['code'] === 2) {
				// 		this.order.delete((a) => a.key === key);
				// 	}
				// }

			}
			this.userInfo = this.user.getuserInfo();
			this.login();
		}
	}

	/**
	 * 上传订单
	 */
	async uploadOrder() {
		// 上传订单
		let b = await this.order.find((order) => order.key !== '' && order.upload == 0)//找出订单信息 0没有上传
		if (b.length > 0) {
			for (var i = 0; i < b.length; i++) {
				const key = b[i].key;
				b[i].index = i;
				let res = await this.http.postJson('', 'member/memberch/create', b[i], '');
				// this.dialog.showAlert('order', JSON.stringify(res));
				if (res['status'] === 200) {
					this.order.delete((a) => a.key === key);
				}
				//登录时把订单信息存入服务器
			}
			this.userInfo = this.user.getuserInfo();
			this.login();
		}
	}



}


export class user_info {
	member_id: any;
	nickname: any;
	phone: any;
	balance: any;
	local_balance: any;
	member_state: any;
	created_at: any;
	updated_at: any;
	cuser_id: any;
	uuser_id: any;
	is_del: any;
	password: any;
	file_type_id: any;
	access_token: any;
	isAutomaticLogon: any;
}